package com.csxh.web.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/*
 * 与web请求与响应有关的工具类
 */
public class WebUtil {

	
	private static final String ORDER = "order";
	private static final String USER = "user";
	private static final String BUY_CART = "buy";
	private static final String PAGER = "pager";
	private static final String AFTER_LOGIN_PAGE = "redirectPage";
	private static final String VERFCODE = "verfcode";

	
	public static void setPager(HttpServletRequest request,Object pager){
		request.setAttribute(PAGER,pager);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getBuyCart(HttpServletRequest request,Class<T> clazz) {
	 Object o=request.getSession().getAttribute(BUY_CART);
	 if(o==null){
		 try {
			o= clazz.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
	 }
		
		return (T)o;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getBuyCart(HttpSession session,Class<T> clazz){
		
		Object o=session.getAttribute(BUY_CART);
		 if(o==null){
			 try {
				o= clazz.newInstance();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
		 }
			
			return (T)o;
		
	}
	
	public static void setBuyCart(HttpServletRequest request,Object buyCart){
		request.getSession().setAttribute(BUY_CART,buyCart);
	}
	public static void setBuyCart(HttpSession session,Object buyCart){
		session.setAttribute(BUY_CART,buyCart);
	}
	@SuppressWarnings("unchecked")
	public static <T> T getUser(HttpServletRequest request){
		return (T)request.getSession().getAttribute(USER);
	}
	
	public static void setUser(HttpServletRequest request,Object user){
		request.getSession().setAttribute(USER,user);
	}

	public static void setUser(HttpSession session,Object user){
		session.setAttribute(USER,user);
	}
	
	public static boolean checkLogin(HttpServletRequest request){
		return null!=request.getSession().getAttribute(USER);
	}
	
	
	@SuppressWarnings("unchecked")
	public static <T> T getOrder(HttpServletRequest request){
		return (T)request.getSession().getAttribute(ORDER);
	}
	
	public static void setOrder(HttpServletRequest request,Object order){
		request.getSession().setAttribute(ORDER,order);
	}
	
	public static String buildLoginUrl(String loginPage, String redirectPage) {
		return loginPage + "?" + AFTER_LOGIN_PAGE + "=" + redirectPage;
	}

	public static String getAfterLoginRedirectPage(HttpServletRequest request) {
		String redirectPage=request.getParameter(AFTER_LOGIN_PAGE);
		return redirectPage;
	}

	public static String getAfterLoginRedirectPage(HttpServletRequest request,String defaultPage) {
		String redirectPage=request.getParameter(AFTER_LOGIN_PAGE);
		if(redirectPage==null || redirectPage.length()==0){
			redirectPage=defaultPage;
		}
		return redirectPage;
		
	}

	public static void logout(HttpServletRequest request){
		request.getSession().setAttribute(USER, null);
		request.getSession().setAttribute(BUY_CART, null);
		request.getSession().setAttribute(ORDER, null);
		request.getSession().invalidate();
	}
	
	//保存记住我的状态
	public static void rememberMe(ServletRequest req, ServletResponse res, Object user) {
		// 说明要记住用户的登录名称与密码
		// 1、在session设置登录成功标记，并将用户对象保存起来
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		
		session.setAttribute(USER, user);
		// 2、将成功标记发给浏览保存
		Cookie c = new Cookie(USER, request.getSession().getId());
		response.addCookie(c);
	}

	/*
	 * checkRememberMe(req,res,R.loginedKey,R.userKey,u)
	 */
	//判断是否记住我了，如果记住了就转向指定的页
	@SuppressWarnings("incomplete-switch")
	public static boolean checkRemeberMe(ServletRequest req, ServletResponse res, String loginedKey, String userKey,
			String path, DispatcherType dispatcherType) {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		HttpSession session = request.getSession();
		// 1、判断session中是否保存了上一次登录成功的标记
		Cookie[] cs = request.getCookies();
		if (null != cs ) {
			// 2、再判断cookie中是否也存在该标记值
			for (Cookie c : cs) {
				if (c.getName().equals(USER) && c.getValue().equals(session.getId())) {
					
					RequestDispatcher rd = request.getRequestDispatcher(path);

					try {

						switch (dispatcherType) {

						case FORWARD:
							rd.forward(request, response);
							break;
						case INCLUDE:
							rd.include(request, response);
							break;

						}

					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						// 请求转发到jsp页面进行响应数据的生成
						// request.removeAttribute(userKey);
						return false;
					}
					return true;
				}
			}

		}

		return false;
	}
	
	
	// 产生随机验证码图片
		public static void buildVerfCodeImage(int width, int height, int codeNum, HttpServletRequest request,
				HttpServletResponse response) throws IOException {

			int fontHeight = height - 2;
			int codeY = height - 4;
			// 定义验证码图像的缓冲流
			BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			// 产生图形上下文
			Graphics2D g = buffImg.createGraphics();

			// 创建随机数产生函数
			Random random = new Random();

			// 将验证码图像背景填充为白色
			g.setColor(Color.WHITE);
			g.fillRect(0, 0, width, height);
			// 为验证码图片画边框，为一个像素。
			g.setColor(Color.BLUE);
			g.drawRect(0, 0, width - 1, height - 1);

			// 随机生产222跳图片干扰线条，使验证码图片中的字符不被轻易识别
			g.setColor(Color.BLACK);
			for (int i = 0; i < 50; i++) {
				int x1 = random.nextInt(width);
				int y1 = random.nextInt(height);
				int x2 = random.nextInt(12);
				int y2 = random.nextInt(12);
				g.drawLine(x1, y1, x1 + x2, y1 + y2);
			}

			char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
					'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', };
			// randomCode保存随机产生的验证码
			StringBuffer randomCode = new StringBuffer();

			// 定义颜色三素
			int red = 0, green = 0, blue = 0;
			int x = width / (codeNum + 1);
			// 创建字体格式，字体的大小则根据验证码图片的高度来设定。
			Font font = new Font(Font.SANS_SERIF, Font.BOLD, fontHeight);
			// 设置字体。
			g.setFont(font);

			// 随机生产codeNum个数字验证码
			for (int i = 0; i < codeNum; i++) {
				// 得到随机产生的验证码
				String strRand = Character.toString(codeSequence[random.nextInt(codeSequence.length)]);
				// 使用随机函数产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。
				red = random.nextInt(255);
				green = random.nextInt(255);
				blue = random.nextInt(255);

				// 用随机产生的颜色将验证码绘制到图像中。
				g.setColor(new Color(red, green, blue));
				g.drawString(strRand, (i + 1) * x, codeY);
				// 将产生的四个随机数组合在一起。
				randomCode.append(strRand);
			}

			System.out.println(randomCode);

			// 将生产的验证码保存到Session中
			HttpSession session = request.getSession();
			session.setAttribute(VERFCODE, randomCode.toString());

			// 设置图像缓存为no-cache。
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);

			response.setContentType("image/jpeg");
			// 将最终生产的验证码图片输出到Servlet的输出流中
			ServletOutputStream sos = response.getOutputStream();

			// ImageIO.write(buffImg, "jpeg", sos);

			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
			encoder.encode(buffImg);
			sos.close();

		}

		public static boolean checkVerfCode(String inputCode, HttpServletRequest request) {

			HttpSession session = request.getSession();
			Object saveCode = session.getAttribute(VERFCODE);
			return (saveCode != null && saveCode.toString().equalsIgnoreCase(inputCode));

		}

	}
